<?php
/**
 * Created by lzl
 * Date: 2021 2021/10/15
 * Time: 16:17
 */
namespace App\Forms;

use App\Exceptions\RequestException;
use App\Models\Cart;
use App\Models\GoodsSkuDetail;

class CartForms extends BaseForm
{

    /**
     * @param $validated
     * @param $uid
     * @return bool
     * @throws RequestException
     */
    public function addOrEditCart($validated, $uid)
    {
        $count = $validated['count'];

        $type = $validated['type'] ?? null;

        $data = array_merge(['goods_id' => $validated['goods_id'], 'attribute_id' => $validated['attribute_id']], compact('uid'));

        $cart = Cart::where($data)->first();

        \DB::beginTransaction();
        try {

            if (filled($cart)) {

                if($type){ //累加
                    $count = $cart->count + $validated['count'];
                }

                //处理库存
                (new StockForms())->editStock($validated['attribute_id'], (int)($cart->count - $count));

                if (!$count) {

                    $cart->delete();

                }else{

                    $cart->update(compact('count'));

                }



            }else{

                //处理库存
                (new StockForms())->editStock($validated['attribute_id'], (0 - $count));

                Cart::create(array_merge($data, compact('count')));

            }

            \DB::commit();

            return true;

        } catch (\Exception $e) {
            \DB::rollBack();

            throw new RequestException($e->getMessage());
        }

    }


    /**
     * 删除购物车
     * @param string|array $ids
     * @return bool
     * @throws RequestException
     */
    public function deleteCart($ids)
    {
        try {

            \DB::beginTransaction();

            $ids = is_array($ids) ? $ids : [$ids];

            foreach ($ids as $item) {
                $cart = Cart::find($item);
                (new StockForms())->editStock($cart->attribute_id, $cart->count);
                $cart->delete();
            }

            \DB::commit();
            return true;
        }catch (\Exception $e){

            \DB::rollBack();

            throw new RequestException($e->getMessage());
        }

    }


    public function deleteCartById($cartId)
    {
        return Cart::whereKey($cartId)->delete();
    }

    /**
     * @param $validated
     * @return mixed
     */
    public function cartList($validated)
    {
        $list = Cart::where('uid', $validated['uid'])
            ->page($validated['page'], $validated['limit'])
            ->get(['id', 'uid', 'goods_id', 'attribute_id', 'count', 'status']);

        if(count($list)){
            foreach ($list as &$item){
                $att = (new GoodsAttributeForms())->getGoodsAttributeDetail($item->attribute_id);
                if($att){
                    /**
                     * @var $item Cart TODO 低效代码
                     */

                    $sku_name = '';
                    if($att->attribute_name){
                        foreach (json_decode($att->attribute_name, true) as $items){
                            $sku_name .= (GoodsSkuDetail::find(array_key_first($items))->value. ':'.$items[array_key_first($items)]). ' ';
                        }
                    }

                    $item['goods'] =  array_merge(
                        (new GoodsForms())->getGoodsDetail($item->goods_id)->toArray(),
                        compact('sku_name'),
                        $att->toArray()
                    );
                }else{
                    //todo 删除购物车还是 商品失效规格处做软删除
                    Cart::whereKey($item->id)->delete();
                    unset($item);

                }

            }
        }

        return $list;

    }


    /**
     * @param $validated
     * @return int
     */
    public function cartCount($validated)
    {
        return Cart::where('uid', $validated['uid'])->sum('count');
    }


    /**
     * 购物车详情
     * @param $cartId
     * @param string $field
     * @return Cart|\Illuminate\Database\Eloquent\Builder|\Illuminate\Database\Eloquent\Model|object|null
     */
    public function cartDetail($cartId, $field = ['*'])
    {
        return Cart::whereKey($cartId)->first($field);
    }

}